{% extends "base.html" %}

{% block title %}三班制排班 - 算法生成照护计划{% endblock %}

{% block page_title %}三班制智能排班{% endblock %}

{% block extra_css %}
<style>
    .form-section {
        margin-bottom: 20px;
        padding: 15px;
        border: 1px solid var(--tech-border);
        border-radius: 5px;
        background-color: rgba(1, 1, 43, 0.75);
    }

    #loading {
        display: none;
        text-align: center;
        margin: 20px 0;
        color: var(--tech-primary);
        visibility: hidden; /* 确保完全隐藏 */
    }

    #loading.hidden {
        display: none !important;
        visibility: hidden !important;
        opacity: 0 !important;
        height: 0 !important;
        overflow: hidden !important;
    }

    .api-panel {
        width: 100%;
        padding: 15px;
        background-color: rgba(1, 1, 43, 0.7);
        border: 1px solid var(--tech-border);
        border-radius: 5px;
        margin: 15px 0;
        color: #fff;
        font-family: monospace;
        white-space: pre-wrap;
        box-shadow: 0 0 10px rgba(5, 238, 255, 0.3);
    }

    .api-url {
        color: var(--tech-accent);
        background-color: rgba(5, 238, 255, 0.1);
        padding: 3px 6px;
        border-radius: 3px;
        font-weight: bold;
    }

    .api-method {
        color: #4CAF50;
        font-weight: bold;
    }

    .shift-time-container {
        display: flex;
        flex-direction: column;
        gap: 10px;
        margin-top: 15px;
        padding: 15px;
        border: 1px solid var(--tech-border);
        border-radius: 5px;
        background-color: rgba(1, 1, 43, 0.6);
    }

    .shift-heading {
        color: var(--tech-primary);
        font-weight: 600;
        margin-bottom: 10px;
        display: flex;
        align-items: center;
    }

    .shift-icon {
        margin-right: 8px;
        font-size: 1.2rem;
    }

    .time-input-group {
        display: flex;
        align-items: center;
        gap: 10px;
        margin-bottom: 10px;
    }

    .time-input-group label {
        min-width: 80px;
        color: #aaa;
    }

    .time-input {
        flex: 1;
        background-color: rgba(1, 1, 43, 0.7);
        border: 1px solid var(--tech-border);
        color: #fff;
        border-radius: 4px;
        padding: 6px 10px;
    }

    .shift-duration {
        margin-left: 10px;
        font-size: 0.85rem;
        color: #aaa;
    }

    .form-label {
        color: var(--tech-primary);
        font-weight: 500;
    }

    .form-control, .form-select {
        background-color: rgba(1, 1, 43, 0.7);
        border: 1px solid var(--tech-border);
        color: #fff;
    }

    .form-control:focus, .form-select:focus {
        background-color: rgba(1, 1, 43, 0.9);
        border-color: var(--tech-primary);
        color: #fff;
        box-shadow: 0 0 10px rgba(5, 238, 255, 0.5);
    }

    /* 响应区域样式 */
    .response-container {
        padding: 15px;
        border: 1px solid var(--tech-border);
        border-radius: 5px;
        background-color: rgba(1, 1, 43, 0.8);
        box-shadow: 0 0 15px rgba(5, 238, 255, 0.3);
        margin-top: 20px;
        display: none;
    }

    .response-header {
        color: var(--tech-primary);
        margin-bottom: 10px;
        font-weight: 600;
        border-bottom: 1px solid var(--tech-border);
        padding-bottom: 10px;
    }

    #api-response {
        font-family: monospace;
        white-space: pre-wrap;
        color: #fff;
        padding: 10px;
        background-color: rgba(5, 238, 255, 0.1);
        border-radius: 5px;
        max-height: 400px;
        overflow-y: auto;
    }

    .tech-badge {
        background-color: rgba(5, 238, 255, 0.2);
        color: var(--tech-primary);
        border: 1px solid var(--tech-border);
        padding: 3px 8px;
        border-radius: 5px;
        font-size: 0.8rem;
    }
</style>
{% endblock %}

{% block content %}
<div class="row">
    <div class="col-md-12">
        <div class="tech-card">
            <div class="tech-card-header">
                <h5 class="card-title"><i class="fas fa-calendar-alt me-2"></i>三班制智能排班算法</h5>
            </div>
            <div class="tech-card-body">
                <div class="row">
                    <div class="col-md-8">
                        <p>本接口使用高级优化算法为养老院生成三班制智能排班计划，支持以下功能：</p>
                        <ul>
                            <li>灵活的班次设置，支持一班、二班、三班和多班模式</li>
                            <li>自定义班次时间范围和时间间隔</li>
                            <li>智能生成护理员排班表和老人照护计划</li>
                            <li>优化的资源分配算法，确保护理质量和资源利用</li>
                            <li>与原有排班系统完全兼容</li>
                        </ul>
                    </div>
                    <div class="col-md-4">
                        <div class="api-panel">
API接口: <span class="api-url">/generate_three_shift_schedule</span>
方法: <span class="api-method">POST</span>
格式: JSON</div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row mt-4">
    <div class="col-md-12">
        <div class="tech-card">
            <div class="tech-card-header">
                <h5 class="card-title"><i class="fas fa-cogs me-2"></i>排班参数配置</h5>
            </div>
            <div class="tech-card-body">
                <ul class="nav nav-tabs" id="myTab" role="tablist">
                    <li class="nav-item" role="presentation">
                        <a class="nav-link active" id="schedule-tab" data-toggle="tab" href="#schedule" role="tab" aria-controls="schedule" aria-selected="true">三班制排班</a>
                    </li>
                    <li class="nav-item" role="presentation">
                        <a class="nav-link" id="elder-tab" data-toggle="tab" href="#elder" role="tab" aria-controls="elder" aria-selected="false">老人需求信息</a>
                    </li>
                    <li class="nav-item" role="presentation">
                        <a class="nav-link" id="attendant-tab" data-toggle="tab" href="#attendant" role="tab" aria-controls="attendant" aria-selected="false">护理员技能</a>
                    </li>
                    <li class="nav-item" role="presentation">
                        <a class="nav-link" id="result-tab" data-toggle="tab" href="#result" role="tab" aria-controls="result" aria-selected="false">请开始</a>
                    </li>
                </ul>
                <div class="tab-content" id="myTabContent">
                    <div class="tab-pane fade show active" id="schedule" role="tabpanel" aria-labelledby="schedule-tab">
                        <form id="threeShiftForm">
                            <div class="form-section">
                                <h6 class="text-light mb-4">排班参数配置</h6>
                                <p class="text-muted">系统将使用全局配置的排班日期、天数和人员限制参数</p>
                            </div>

                            <div class="form-section">
                                <h6 class="text-light mb-4">班次设置</h6>
                                <div class="row mb-3">
                                    <div class="col-md-6">
                                        <label for="shift_mode" class="form-label">班制模式</label>
                                        <select class="form-select" id="shift_mode" name="shift_mode">
                                            <option value="1">一班制</option>
                                            <option value="2">二班制</option>
                                            <option value="3" selected>三班制</option>
                                        </select>
                                    </div>
                                    <div class="col-md-6">
                                        <label for="time_interval_minutes" class="form-label">时间间隔（分钟）</label>
                                        <div class="input-group">
                                            <select class="form-select" id="time_interval_minutes" name="time_interval_minutes">
                                                <option value="10">10</option>
                                                <option value="12">12</option>
                                                <option value="15">15</option>
                                                <option value="20" selected>20</option>
                                                <option value="30">30</option>
                                                <option value="40">40</option>
                                                <option value="50">50</option>
                                                <option value="60">60</option>
                                            </select>
                                            <button class="btn btn-outline-secondary" type="button" id="manual_input_btn">手动输入</button>
                                        </div>
                                        <input type="number" class="form-control mt-2" id="manual_time_interval" name="manual_time_interval" min="10" max="60" placeholder="手动输入(10-60分钟)" style="display:none;">
                                        <small class="text-muted">每个时间段的长度</small>
                                    </div>
                                </div>

                                <div class="shift-time-container">
                                    <div class="shift-heading">
                                        <i class="fas fa-sun shift-icon"></i>早班时间设置
                                    </div>
                                    <div class="time-input-group">
                                        <label>开始时间</label>
                                        <input type="time" class="time-input" id="shift1_start" name="shift1_start" value="06:00">
                                        <label>结束时间</label>
                                        <input type="time" class="time-input" id="shift1_end" name="shift1_end" value="14:00">
                                        <span class="shift-duration" id="shift1_duration">时长: 8小时</span>
                                    </div>
                                </div>

                                <div class="shift-time-container" id="shift2_container">
                                    <div class="shift-heading">
                                        <i class="fas fa-cloud-sun shift-icon"></i>中班时间设置
                                    </div>
                                    <div class="time-input-group">
                                        <label>开始时间</label>
                                        <input type="time" class="time-input" id="shift2_start" name="shift2_start" value="14:00">
                                        <label>结束时间</label>
                                        <input type="time" class="time-input" id="shift2_end" name="shift2_end" value="22:00">
                                        <span class="shift-duration" id="shift2_duration">时长: 8小时</span>
                                    </div>
                                </div>

                                <div class="shift-time-container" id="shift3_container">
                                    <div class="shift-heading">
                                        <i class="fas fa-moon shift-icon"></i>夜班时间设置
                                    </div>
                                    <div class="time-input-group">
                                        <label>开始时间</label>
                                        <input type="time" class="time-input" id="shift3_start" name="shift3_start" value="22:00">
                                        <label>结束时间</label>
                                        <input type="time" class="time-input" id="shift3_end" name="shift3_end" value="06:00">
                                        <span class="shift-duration" id="shift3_duration">时长: 8小时</span>
                                    </div>
                                </div>
                            </div>

                            <div class="form-section">
                                <h6 class="text-light mb-4">数据限制</h6>
                                <p class="text-muted">系统将使用全局配置的数据限制参数，包括护理员偏好、工作负荷平衡、照护覆盖和排班冲突等</p>
                            </div>

                            <div class="d-grid gap-2">
                                <button type="submit" class="btn tech-btn tech-btn-primary" id="submitButton">
                                    <i class="fas fa-calendar-plus me-2"></i>开始排班
                                </button>
                            </div>
                        </form>

                        <div id="loading" class="mt-4" style="display: none;">
                            <div class="spinner-border text-primary" role="status" id="loading-spinner">
                                <span class="visually-hidden">正在生成排班...</span>
                            </div>
                            <p class="mt-2" id="loading-text">正在生成排班，请稍候...</p>
                            <button type="button" class="btn tech-btn tech-btn-danger btn-sm mt-2" id="cancelButton">
                                <i class="fas fa-times-circle me-1"></i>中断排班
                            </button>
                        </div>

                        <div class="response-container" id="responseContainer">
                            <div class="response-header">
                                <i class="fas fa-code me-2"></i>API 响应结果
                            </div>
                            <div id="api-response"></div>
                        </div>
                    </div>
                    <div class="tab-pane fade" id="elder" role="tabpanel" aria-labelledby="elder-tab">
                        <!-- Content for the "elder" tab -->
                    </div>
                    <div class="tab-pane fade" id="attendant" role="tabpanel" aria-labelledby="attendant-tab">
                        <!-- Content for the "attendant" tab -->
                    </div>
                    <div class="tab-pane fade" id="result" role="tabpanel" aria-labelledby="result-tab">
                        <!-- Content for the "result" tab -->
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    $(document).ready(function() {
        // 全局变量，用于跟踪当前AJAX请求
        let currentAjaxRequest = null;
        let requestCancelled = false;

        // 函数：彻底隐藏加载状态
        function hideLoadingCompletely() {
            // 使用多种方法确保加载状态完全隐藏
            $('#loading').css('display', 'none');
            $('#loading').hide();
            $('#loading').addClass('hidden');
            $('#loading-spinner').css('display', 'none');
            $('#loading-spinner').hide();
            $('.spinner-border').css('display', 'none');
            $('.spinner-border').hide();

            // 移除加载动画类
            $('.spinner-border').removeClass('spinner-border');

            console.log('加载状态已彻底隐藏');
        }
        // 计算班次时长
        function calculateShiftDuration(startTime, endTime) {
            let start = new Date('2000-01-01 ' + startTime);
            let end = new Date('2000-01-01 ' + endTime);

            // 处理跨越午夜的情况
            if (end < start) {
                end = new Date('2000-01-02 ' + endTime);
            }

            let diff = (end - start) / (1000 * 60 * 60); // 转换为小时
            return diff.toFixed(1);
        }

        // 更新班次时长显示
        function updateShiftDurations() {
            let shift1Start = $('#shift1_start').val();
            let shift1End = $('#shift1_end').val();
            let shift2Start = $('#shift2_start').val();
            let shift2End = $('#shift2_end').val();
            let shift3Start = $('#shift3_start').val();
            let shift3End = $('#shift3_end').val();

            if (shift1Start && shift1End) {
                let duration = calculateShiftDuration(shift1Start, shift1End);
                $('#shift1_duration').text('时长: ' + duration + '小时');
            }

            if (shift2Start && shift2End) {
                let duration = calculateShiftDuration(shift2Start, shift2End);
                $('#shift2_duration').text('时长: ' + duration + '小时');
            }

            if (shift3Start && shift3End) {
                let duration = calculateShiftDuration(shift3Start, shift3End);
                $('#shift3_duration').text('时长: ' + duration + '小时');
            }
        }

        // 班制模式切换
        $('#shift_mode').change(function() {
            const mode = $(this).val();

            // 根据班制模式显示或隐藏对应的班次设置
            if (mode === '1') {
                $('#shift2_container, #shift3_container').hide();
            } else if (mode === '2') {
                $('#shift2_container').show();
                $('#shift3_container').hide();
            } else {
                $('#shift2_container, #shift3_container').show();
            }
        });

        // 初始化班次时长
        updateShiftDurations();

        // 在时间输入变化时更新时长
        $('.time-input').change(updateShiftDurations);

        // 页面加载完成后立即隐藏加载状态
        hideLoadingCompletely();

        // 中断按钮点击事件
        $('#cancelButton').click(function() {
            if (currentAjaxRequest) {
                // 标记请求已取消
                requestCancelled = true;

                // 中断AJAX请求
                currentAjaxRequest.abort();
                currentAjaxRequest = null;

                // 更新UI状态
                $('#loading-text').text('排班已中断');
                setTimeout(function() {
                    // 彻底隐藏加载状态
                    hideLoadingCompletely();

                    // 启用提交按钮并恢复按钮文本
                    $('button[type="submit"]').prop('disabled', false);
                    $('#submitButton').html('<i class="fas fa-calendar-plus me-2"></i>开始排班');
                    console.log('排班已中断，已彻底隐藏加载状态，恢复按钮文本');
                }, 1000);

                console.log('用户中断了排班请求');
            }
        });

        // 表单提交
        $('#threeShiftForm').submit(function(e) {
            e.preventDefault();

            // 显示加载中
            $('#loading').show();
            $('#loading-spinner').show(); // 确保加载图标显示
            $('#responseContainer').hide();

            // 修改提交按钮文本为"提交中..."
            $('#submitButton').html('<i class="fas fa-spinner fa-spin me-2"></i>提交中...');

            // 获取表单数据
            const formData = {};
            $(this).serializeArray().forEach(function(item) {
                formData[item.name] = item.value;
            });

            // 处理班次设置
            const shiftMode = parseInt(formData.shift_mode);
            formData.shift_mode = shiftMode;

            // 创建自定义班次数组
            const customShifts = [];

            // 总是添加班次1
            customShifts.push({
                name: "1",
                start_time: formData.shift1_start,
                end_time: formData.shift1_end
            });

            // 根据班制模式添加其他班次
            if (shiftMode >= 2) {
                customShifts.push({
                    name: "2",
                    start_time: formData.shift2_start,
                    end_time: formData.shift2_end
                });
            }

            if (shiftMode >= 3) {
                customShifts.push({
                    name: "3",
                    start_time: formData.shift3_start,
                    end_time: formData.shift3_end
                });
            }

            formData.custom_shifts = customShifts;

            // 数据限制参数使用全局配置

            // 转换数字类型
            formData.time_interval_minutes = parseInt(formData.time_interval_minutes);

            // 清理不需要发送的表单字段
            delete formData.shift1_start;
            delete formData.shift1_end;
            delete formData.shift2_start;
            delete formData.shift2_end;
            delete formData.shift3_start;
            delete formData.shift3_end;

            // 打印请求数据到控制台，方便调试
            console.log('发送的请求数据:', formData);

            // 构建简化的请求数据
            const requestData = {
                shift_mode: formData.shift_mode,
                custom_shifts: formData.custom_shifts,
                time_interval_minutes: formData.time_interval_minutes,
                generate_care_timeline: true
            };

            console.log('简化后的请求数据:', requestData);

            // 重置取消标志
            requestCancelled = false;

            // 更新加载状态文本
            $('#loading-text').text('正在生成排班，请稍候...');

            // 发送请求
            currentAjaxRequest = $.ajax({
                url: '/simple_three_shift_schedule', // 改用简化版接口
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(requestData),
                // 添加完成回调，确保无论成功、失败还是中断，都能隐藏加载状态
                complete: function() {
                    // 彻底隐藏加载状态
                    hideLoadingCompletely();

                    // 启用提交按钮并恢复按钮文本
                    $('button[type="submit"]').prop('disabled', false);
                    $('#submitButton').html('<i class="fas fa-calendar-plus me-2"></i>开始排班');
                    console.log('请求完成，确保加载状态已彻底隐藏，恢复按钮文本');
                },
                success: function(response) {
                    // 如果请求已被取消，不处理响应
                    if (requestCancelled) {
                        console.log('请求已被用户取消，忽略响应');
                        return;
                    }

                    // 清除当前请求引用
                    currentAjaxRequest = null;

                    // 彻底隐藏加载状态，显示响应
                    hideLoadingCompletely();
                    $('#responseContainer').show();

                    console.log('排班成功，已彻底隐藏加载状态');

                    // 格式化JSON并显示
                    const formattedJson = JSON.stringify(response, null, 2);
                    $('#api-response').html(syntaxHighlight(formattedJson));

                    // 显示成功消息
                    const successAlert = `
                        <div class="alert tech-alert tech-alert-success mt-3 mb-3">
                            <i class="fas fa-check-circle me-2"></i>三班制排班生成成功！
                        </div>
                    `;
                    $('#responseContainer').prepend(successAlert);

                    // 显示生成的排班数据摘要
                    if (response.shift_assignments && response.shift_assignments.length > 0) {
                        const summaryAlert = `
                            <div class="alert tech-alert tech-alert-info mt-3">
                                <i class="fas fa-info-circle me-2"></i>成功生成 ${response.shift_assignments.length} 条护理员排班记录
                            </div>
                        `;
                        $('#responseContainer').append(summaryAlert);
                    }

                    // 启用提交按钮
                    $('button[type="submit"]').prop('disabled', false);
                },
                error: function(xhr, status, error) {
                    // 如果请求已被取消或状态为"abort"，不显示错误
                    if (requestCancelled || status === 'abort') {
                        console.log('请求已被用户取消或中断');
                        return;
                    }

                    // 清除当前请求引用
                    currentAjaxRequest = null;

                    // 彻底隐藏加载状态，显示响应
                    hideLoadingCompletely();
                    $('#responseContainer').show();

                    console.log('排班失败，已彻底隐藏加载状态');

                    console.error('请求失败:', error);
                    console.error('状态码:', xhr.status);
                    console.error('响应内容:', xhr.responseText);

                    // 显示错误消息
                    let errorMsg = '未知错误';
                    if (xhr.responseJSON && xhr.responseJSON.error) {
                        errorMsg = xhr.responseJSON.error;
                    } else if (xhr.responseText) {
                        try {
                            const errorObj = JSON.parse(xhr.responseText);
                            errorMsg = errorObj.error || errorObj.message || xhr.responseText;
                        } catch (e) {
                            errorMsg = xhr.responseText;
                        }
                    }

                    const errorAlert = `
                        <div class="alert tech-alert tech-alert-danger mt-3 mb-3">
                            <i class="fas fa-exclamation-triangle me-2"></i>排班生成失败: ${errorMsg}
                        </div>
                    `;
                    $('#responseContainer').prepend(errorAlert);

                    // 显示错误详情
                    if (xhr.responseJSON) {
                        const formattedJson = JSON.stringify(xhr.responseJSON, null, 2);
                        $('#api-response').html(syntaxHighlight(formattedJson));
                    } else if (xhr.responseText) {
                        try {
                            const errorObj = JSON.parse(xhr.responseText);
                            const formattedJson = JSON.stringify(errorObj, null, 2);
                            $('#api-response').html(syntaxHighlight(formattedJson));
                        } catch (e) {
                            $('#api-response').text(xhr.responseText);
                        }
                    } else {
                        $('#api-response').text(`请求失败: ${error}, 状态码: ${xhr.status}`);
                    }

                    // 添加重试按钮
                    const retryButton = `
                        <div class="d-grid gap-2 mt-3">
                            <button type="button" class="btn tech-btn tech-btn-warning" id="retryButton">
                                <i class="fas fa-sync-alt me-2"></i>重试
                            </button>
                        </div>
                    `;
                    $('#responseContainer').append(retryButton);

                    // 绑定重试按钮事件
                    $('#retryButton').click(function() {
                        $('#threeShiftForm').submit();
                    });

                    // 启用提交按钮
                    $('button[type="submit"]').prop('disabled', false);
                }
            });

            // 禁用提交按钮，防止重复提交
            $('button[type="submit"]').prop('disabled', true);
        });

        // 语法高亮函数
        function syntaxHighlight(json) {
            if (typeof json != 'string') {
                json = JSON.stringify(json, undefined, 2);
            }
            json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
            return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function(match) {
                let cls = 'text-white';
                if (/^"/.test(match)) {
                    if (/:$/.test(match)) {
                        cls = 'text-info';  // 键名
                    } else {
                        cls = 'text-warning'; // 字符串
                    }
                } else if (/true|false/.test(match)) {
                    cls = 'text-success';  // 布尔值
                } else if (/null/.test(match)) {
                    cls = 'text-danger';   // null
                } else if (/-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/.test(match)) {
                    cls = 'text-primary';  // 数字
                }
                return '<span class="' + cls + '">' + match + '</span>';
            });
        }

        // 手动输入按钮点击事件
        document.getElementById('manual_input_btn').addEventListener('click', function() {
            const selectElement = document.getElementById('time_interval_minutes');
            const manualInputElement = document.getElementById('manual_time_interval');
            
            if (manualInputElement.style.display === 'none') {
                // 显示手动输入框
                manualInputElement.style.display = 'block';
                selectElement.disabled = true;
                this.textContent = '使用下拉选择';
                
                // 将下拉框的值复制到手动输入框
                manualInputElement.value = selectElement.value;
            } else {
                // 隐藏手动输入框
                manualInputElement.style.display = 'none';
                selectElement.disabled = false;
                this.textContent = '手动输入';
                
                // 如果手动输入框有有效值，更新下拉框
                const manualValue = parseInt(manualInputElement.value);
                if (!isNaN(manualValue) && manualValue >= 10 && manualValue <= 60) {
                    // 尝试查找匹配的选项
                    let optionFound = false;
                    for (let option of selectElement.options) {
                        if (parseInt(option.value) === manualValue) {
                            selectElement.value = option.value;
                            optionFound = true;
                            break;
                        }
                    }
                    
                    // 如果没有匹配的选项，添加一个新选项
                    if (!optionFound) {
                        const newOption = new Option(manualValue.toString(), manualValue.toString());
                        selectElement.add(newOption);
                        selectElement.value = manualValue.toString();
                    }
                }
            }
        });
        
        // 表单提交时的处理
        document.querySelector('form').addEventListener('submit', function(e) {
            const selectElement = document.getElementById('time_interval_minutes');
            const manualInputElement = document.getElementById('manual_time_interval');
            
            // 如果手动输入框可见且有有效值，使用手动输入的值
            if (manualInputElement.style.display !== 'none') {
                const manualValue = parseInt(manualInputElement.value);
                if (!isNaN(manualValue) && manualValue >= 10 && manualValue <= 60) {
                    // 更新下拉框的值以匹配手动输入
                    let optionFound = false;
                    for (let option of selectElement.options) {
                        if (parseInt(option.value) === manualValue) {
                            selectElement.value = option.value;
                            optionFound = true;
                            break;
                        }
                    }
                    
                    if (!optionFound) {
                        const newOption = new Option(manualValue.toString(), manualValue.toString());
                        selectElement.add(newOption);
                        selectElement.value = manualValue.toString();
                    }
                    
                    // 启用下拉框以确保其值被提交
                    selectElement.disabled = false;
                }
            }
        });
    });
</script>
{% endblock %}
